#!/usr/bin/env python
# -*- coding: UTF-8 -*-
"""
@File    ：chat_message_repo.py
@Author  ：平
@Date    ：2025/10/2 19:57 
"""
from sqlalchemy import select

from sqlalchemy.sql.expression import cast
from sqlalchemy.sql.functions import func
from sqlalchemy.sql.sqltypes import Interval

from app.config.config import Session
from app.model.chat_message import ChatMessage


def query_messages_by_mix(thread_id: str, limit: int = 10) -> list[ChatMessage]:
    """
    通过 user_id 和 thread_id 查询 limit 个消息，并按创建时间降序排序
    Args:
        thread_id: 会话id
        limit: 限制长度

    Returns:
        List[ChatMessage]: 消息列表，按创建时间降序排列
    """
    with Session() as session:
        if limit < 0:
            return session.query(ChatMessage).filter(ChatMessage.thread_id == thread_id).order_by(
                ChatMessage.created_at.asc()).all()
        else:
            return session.query(ChatMessage).filter(ChatMessage.thread_id == thread_id).order_by(
                ChatMessage.created_at.desc()).limit(limit).all()


def save_message(user_id: int, thread_id: str, title: str = None, agent: str = None,
                 role: str = None, content: str = None, finish_reason: str = None) -> ChatMessage:
    """
    保存消息
    Args:
        user_id: 用户id
        thread_id: 会话id
        title: 会话标题
        agent: 智能体名称
        role: 角色
        content: 消息内容
        finish_reason: 结束原因
    """
    message = ChatMessage(user_id=user_id, thread_id=thread_id, title=title, agent=agent, role=role, content=content,
                          finish_reason=finish_reason)
    with Session() as session:
        with session.begin():
            session.add(message)
        session.refresh(message)
    return message


def query_conversation_by_user_id(user_id: int, days: int = 7) -> list:
    """
    通过 user_id 查询最近 day 天会话列表
    Args:
        user_id: 用户id
        days：天数

    Returns:
        List[ChatMessage]: 会话列表
    """
    with Session() as session:
        return [dict(row) for row in session.execute(
            select(
                ChatMessage.thread_id.label('threadId'),
                ChatMessage.title,
                func.min(ChatMessage.created_at).label('createdAt')
            ).where(ChatMessage.user_id == user_id)
            .group_by(
                ChatMessage.thread_id,
                ChatMessage.title
            )
            .having(
                func.min(ChatMessage.created_at) >= func.now() - cast(func.text(f"{days} days"), Interval)
            )
            .order_by(
                func.min(ChatMessage.created_at).desc()
            )
        ).mappings().all()]
